package org.redmagic.common;

import java.io.IOException;

import org.redmagic.common.MagicProperty.Serializer;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using=Serializer.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MagicProperty {

	private static final String UTF_8 = "UTF-8";

	private final String name;
	private final String value;
	private final String encoding;

	public MagicProperty(String name, String value) {
		this(name, value, UTF_8);
	}

	public MagicProperty(@JsonProperty("name") String name,
			@JsonProperty("value") String value,
			@JsonProperty("encoding") String encoding) {
		this.name = name;
		this.value = value;
		this.encoding = encoding;
	}

	public String getName() {
		return name;
	}

	public String getValue() {
		return value;
	}

	public String getEncoding() {
		return encoding;
	}

	@Override
	public String toString() {
		return name + ": " + value;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((encoding == null) ? 0 : encoding.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MagicProperty other = (MagicProperty) obj;
		if (encoding == null) {
			if (other.encoding != null)
				return false;
		} else if (!encoding.equals(other.encoding))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		return true;
	}
	
	protected static class Serializer extends JsonSerializer<MagicProperty> {
		@Override
		public void serialize(MagicProperty property, JsonGenerator jgen,
				SerializerProvider provider) throws IOException,
				JsonProcessingException {

			jgen.writeStartObject();
			jgen.writeStringField("name", property.getName());
			jgen.writeStringField("value", property.getValue());
			jgen.writeStringField("encoding", property.getEncoding());
			jgen.writeEndObject();
		}
	}
}
